<template>
    <div ref="chart" class="chart"></div>
  </template>
  
  <script lang="ts">
  import { defineComponent, onMounted, ref, watch, nextTick } from 'vue';
  import * as echarts from 'echarts';
  
  export default defineComponent({
    name: 'ECharts',
    props: {
      option: {
        type: Object,
        required: true
      }
    },
    setup(props) {
      const chart = ref<HTMLDivElement | null>(null);
      let myChart: echarts.ECharts | null = null;
  
      onMounted(() => {
        nextTick(() => {
          if (chart.value) {
            myChart = echarts.init(chart.value);
            myChart.setOption(props.option);
            // 当用户点击图表时启用数据缩放（如果需要）
            const zoomSize = 6;
            myChart.on('click', function (params) {
              myChart?.dispatchAction({
                type: 'dataZoom',
                startValue: Math.max(params.dataIndex - zoomSize / 2, 0),
                endValue: Math.min(params.dataIndex + zoomSize / 2, (props.option.xAxis?.data?.length || 0) - 1)
              });
            });
          }
        });
      });
  
      watch(() => props.option, (newOption) => {
        if (myChart) {
          myChart.setOption(newOption, true); // 第二个参数为 true 表示合并新旧选项
        }
      }, { deep: true });
  
      return {
        chart
      };
    }
  });
  </script>
  
  <style scoped>
  .chart {
    width: 100%;
    height: 100%;
    /* border: 1px solid red; */
  }
  </style>
  